<template>
  <div
    :class="[
      'wrapper',
      placement === 'top' ? 'top' : placement === 'bottom' ? 'bottom' : ''
    ]"
    :style="{ backgroundColor: wrapperColor }"
  >
    <div
      class="scale-ctn"
      :style="{ width: formatWidth + 'px', height: formatHeight + 'px' }"
    >
      <div
        class="scale-box"
        :style="{
          transform: 'scale(' + scale + ',  ' + scale + ')',
          width: width + 'px',
          height: height + 'px'
        }"
      >
        <slot></slot>
      </div>
    </div>
  </div>
</template>

<script>
import debounce from 'lodash/debounce'

export default {
  name: 'ScalBox',
  props: {
    width: {
      type: Number,
      default: 1920
    },
    height: {
      type: Number,
      default: 1080
    },
    wrapperColor: {
      // 最外层容器颜色 默认黑色
      type: String,
      default: '#000000'
    },
    placement: {
      // 主视图位置 默认居中
      type: String,
      default: 'center'
    }
  },
  data() {
    return {
      scale: 1
    }
  },
  computed: {
    formatWidth() {
      return this.width * this.scale
    },
    formatHeight() {
      return this.height * this.scale
    }
  },
  watch: {
    scale: {
      handler(newVal) {
        if (newVal) {
          this.$emit('scale-change', newVal)
        }
      }
    }
  },
  mounted() {
    this.scale = this.getScale()
    const setScale = debounce(() => {
      this.scale = this.getScale()
    }, 100)
    window.addEventListener('resize', setScale)
  },
  methods: {
    getScale() {
      const sw = window.innerWidth / this.width
      const sh = window.innerHeight / this.height
      return sw < sh ? sw : sh
    }
  }
}
</script>

<style  lang="less" scoped>
.wrapper {
  width: 100vw;
  height: 100vh;
  overflow: hidden;
  user-select: none;
  display: flex;
  align-items: center;
  justify-content: center;

  &.top {
    align-items: flex-start;
  }

  &.bottom {
    align-items: flex-end;
  }

  .scale-box {
    transform-origin: 0 0;
    transition: all 0.5s;
    overflow: hidden;
  }
}
</style>
